package cn.wolfcode.rbac.web.interceptor;

import cn.wolfcode.rbac.annotation.RequiredPermission;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class SecurityInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee emp = UserContext.getCurrentUser();
        if (emp.isAdmin()){
            return true;
        }
        HandlerMethod hm = (HandlerMethod)handler;
        Method method = hm.getMethod();
        RequiredPermission anno = method.getAnnotation(RequiredPermission.class);
        if (anno == null){
            //访问的方法不需要权限,放行
            return true;
        }
        List<String> exps = UserContext.getExpressions();
        if (exps.contains(anno.value()[1])){
            //当前用户拥有访问权限,放行
            return true;
        }
        //当前用户没有权限方法,不放行
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;
    }
}
